package com.utils;// com.service.TaskQueueManager.java


import com.dto.FlyCircleParam;
import com.dto.FlyLineParam;
import com.dto.FlyRectangleParam;
import com.entity.FlyTask;
import com.service.DroneService;
import com.service.IFlyTaskService;
import net.bytebuddy.asm.Advice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

@Component
public class TaskQueueManager {
    private static final Logger logger = LoggerFactory.getLogger(TaskQueueManager.class);

    // 任务队列
    private final BlockingQueue<Object> taskQueue = new LinkedBlockingQueue<>();

    // 暂停标志（使用volatile保证线程可见性）
    private volatile boolean isPaused = true;

    @Autowired
    private DroneService droneService;

    @Autowired
    private IFlyTaskService iFlyTaskService;

    private Thread taskProcessor;

    private Object currentTask = null;

    @PostConstruct
    public void init() {
        taskProcessor = new Thread(this::processTasks);
        taskProcessor.setName("Drone-Task-Processor");
        taskProcessor.setDaemon(true);
        taskProcessor.start();
        pause();
        logger.info("任务队列管理器初始化完成");
    }

    /**
     * 添加矩形飞行任务
     */
    public void addRectangleTask(FlyRectangleParam param) {
        System.out.println("id:"+param.getId());
        System.out.println("taskId:"+param.getTaskId());
        taskQueue.add(param);
        logger.info("添加矩形飞行任务到队列");
    }

    /**
     * 添加圆形飞行任务
     */
    public void addCircleTask(FlyCircleParam param) {
        System.out.println("id:"+param.getId());
        System.out.println("taskId:"+param.getTaskId());
        taskQueue.add(param);
        logger.info("添加圆形飞行任务到队列");
    }

    /**
     * 添加直线飞行任务
     */
    public void addLineTask(FlyLineParam param) {
        System.out.println("id:"+param.getId());
        System.out.println("taskId:"+param.getTaskId());
        taskQueue.add(param);
        logger.info("添加直线任务到队列，当前队列大小: {}", taskQueue.size()); // 新增日志
    }

    /**
     * 处理队列中的任务
     */
    private void processTasks() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                // 检查是否暂停
                while (isPaused) {
                    Thread.sleep(100); // 暂停期间休眠，避免CPU占用
                }
                // 从队列获取任务（阻塞操作）
                Object task = taskQueue.take();
                currentTask = task;

                // 执行任务
                if (task instanceof FlyRectangleParam) {
                    FlyRectangleParam param = (FlyRectangleParam) task;
                    logger.info("执行矩形飞行任务: {}", param);
                    droneService.flyRectangleByP2P(
                            param.getFlightAltitude(),
                            param.getEndX(), param.getEndY(),
                            param.getCurrent_x(), param.getCurrent_y(),
                            param.isClockwise(),
                            param.getCycle_s()
                    );
                } else if (task instanceof FlyCircleParam) {
                    FlyCircleParam param = (FlyCircleParam) task;
                    logger.info("执行圆形飞行任务: {}", param);
                    droneService.sendflyCircleCmdOnOffBorad(
                            param.getRadius(),
                            param.isClockwise(),
                            param.getCurrent_x(),
                            param.getCurrent_y(),
                            param.getFlightAltitude(),
                            param.getCycle_s(),
                            param.isUuu()
                    );
                } else if (task instanceof FlyLineParam) {
                    FlyLineParam param = (FlyLineParam) task;
                    logger.info("执行直线飞行任务: {}", param);
                    logger.info("param.getStartX():"+param.getStartX()+";param.getStartY()"+param.getStartY());
                    logger.info("param.getEndX():"+param.getEndX()+";param.getEndY()"+param.getEndY());
                    droneService.flyPointToPoint(
                            param.getStartX(), param.getStartY(),
                            param.getEndX(), param.getEndY(),
                            param.getFlightAltitude(),
                            param.getDuration_s()
                    );
                }
                logger.info("任务执行完成");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                logger.warn("任务处理器被中断");
                break;
            } catch (Exception e) {
                logger.error("任务执行失败", e);
            }
        }
    }

    /**
     * 暂停任务队列
     */
    public void pause() {
        isPaused = true;
        logger.info("任务队列已暂停，当前待执行任务数: {}", taskQueue.size());
    }

    /**
     * 恢复任务队列
     */
    public void resume() {
        isPaused = false;
        logger.info("任务队列已恢复，当前待执行任务数: {}", taskQueue.size());
    }

    /**
     * 获取队列中待执行的任务数量
     */
    public int getPendingTaskCount() {
        return taskQueue.size();
    }

    /**
     * 检查队列是否暂停
     */
    public boolean isPaused() {
        return isPaused;
    }


    /**
     * 获取队列中的所有任务（转换为可序列化的DTO）
     */
    public List<TaskInfo> getAllTasks() {
        List<TaskInfo> taskInfos = new ArrayList<>();
        ArrayList<Object> tasks = new ArrayList<>(taskQueue);
        if(currentTask!=null)
            tasks.add(currentTask);
        // 复制队列内容避免并发修改问题
        for (Object task : tasks) {
            if (task instanceof FlyRectangleParam) {
                FlyRectangleParam param = (FlyRectangleParam) task;
                int id = param.getId();
//                System.out.println("id:"+id);
                FlyTask flyTask = iFlyTaskService.getById(param.getTaskId());
                taskInfos.add(new TaskInfo(
                        "RECTANGLE",
                        id,
                        flyTask.getFlyTaskName(),
                        String.format("矩形飞行：从(%.2f,%.2f)到(%.2f,%.2f)",
                                param.getCurrent_x(), param.getCurrent_y(),
                                param.getEndX(), param.getEndY()),
                        flyTask.getFlyStartDate().toInstant(ZoneOffset.UTC).toEpochMilli()) // 简化处理，实际应记录任务创建时间
                );
            } else if (task instanceof FlyCircleParam) {
                FlyCircleParam param = (FlyCircleParam) task;
                int id = param.getId();
//                System.out.println("id:"+id);
                FlyTask flyTask = iFlyTaskService.getById(param.getTaskId());
                taskInfos.add(new TaskInfo(
                        "CIRCLE",
                        id,
                        flyTask.getFlyTaskName(),
                        String.format("圆形飞行：半径%.2f，方向%s", param.getRadius(), param.isClockwise() ? "顺时针" : "逆时针"),
                        flyTask.getFlyStartDate().toInstant(ZoneOffset.UTC).toEpochMilli()
                ));
            } else if (task instanceof FlyLineParam) {
                FlyLineParam param = (FlyLineParam) task;
                int id = param.getId();
//                System.out.println("id:"+id);
                FlyTask flyTask = iFlyTaskService.getById(param.getTaskId());
                taskInfos.add(new TaskInfo(
                        "LINE",
                        id,
                        flyTask.getFlyTaskName(),
                        String.format("直线飞行：从(%.2f,%.2f)到(%.2f,%.2f)",
                                param.getStartX(), param.getStartY(),
                                param.getEndX(), param.getEndY()),
                        flyTask.getFlyStartDate().toInstant(ZoneOffset.UTC).toEpochMilli()
                ));
            }
        }
        return taskInfos;
    }

    // 任务信息DTO类
    public static class TaskInfo {
        private final String type; // 任务类型
        private final int id;      // 任务类型
        private final String taskName;      // 任务类型
        private final String description; // 任务描述
        private final long createTime;  // 创建时间

        public TaskInfo(String type, int id, String taskName, String description, long createTime) {
            this.type = type;
            this.id = id;
            this.taskName = taskName;
            this.description = description;
            this.createTime = createTime;
        }
        // 关键：添加所有属性的公共getter方法
        public String getType() {
            return type;
        }

        public int getId() {
            return id;
        }

        public String getTaskName() {
            return taskName;
        }

        public String getDescription() {
            return description;
        }

        public long getCreateTime() {
            return createTime;
        }
    }
}